package com.book.service.impl;

import com.book.entity.BookCart;
import com.book.mapper.BookCartMapper;
import com.book.service.BookCartService;
import com.book.vo.CartVo;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author SuperYu  2024/8/5
 */
@Service
public class BookCartServiceImpl implements BookCartService {

    @Resource
    BookCartMapper bookCartMapper;

    @Override
    public List<CartVo> findCartByUserId(int userId) {
        return bookCartMapper.selectBookCartByUserId(userId);
    }

    @Override
    public int findCartNumByUserId(int userId) {
        Example example = new Example(BookCart.class);
        Example.Criteria c = example.createCriteria();
        c.andEqualTo("userId", userId);
        c.andNotEqualTo("isDelete", 1);

        return bookCartMapper.selectCountByExample(example);
    }

    @Override
    public int addToCart(BookCart cart) {
        Example example = new Example(BookCart.class);
        Example.Criteria c = example.createCriteria();
        c.andEqualTo("userId", cart.getUserId());
        c.andEqualTo("bookId", cart.getBookId());
        BookCart temp = bookCartMapper.selectOneByExample(example);

        if (temp == null) {
            //2: 如果没有查到，则执行新增操作
            cart.setCreateTime(new Date());
            return bookCartMapper.insertSelective(cart);
        } else {
            //1: 根据用户id和书籍id去查数据，如果查到了执行更新操作
            temp.setBuyCount(temp.getBuyCount() + cart.getBuyCount());
            return bookCartMapper.updateByPrimaryKeySelective(temp);
        }
    }

}
